package com.iwunu.gateway.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.iwunu.gateway.cache.RedisService;
import com.iwunu.gateway.entity.CmdIssued;
import com.iwunu.gateway.entity.FLockMember;
import com.iwunu.gateway.entity.FLockUser;
import com.iwunu.gateway.entity.FaceLock;
import com.iwunu.gateway.entity.ImageMongo;
import com.iwunu.gateway.entity.SystemUser;
import com.iwunu.gateway.service.CmdIssuedMongodbService;
import com.iwunu.gateway.service.FaceLockMemberService;
import com.iwunu.gateway.service.FaceLockService;
import com.iwunu.gateway.service.FlockUserService;
import com.iwunu.gateway.service.ImageMongodbService;
import com.iwunu.gateway.service.SystemUserService;
import com.iwunu.gateway.service.TokenService;
import com.iwunu.gateway.vo.FaceLockVo;
import com.iwunu.gateway.vo.LockUpdateVo;
import com.iwunu.iot.common.constant.ClientOpenTypeEnum;
import com.iwunu.iot.common.constant.ResultCodeEnum;
import com.iwunu.iot.common.util.DESUtil;
import com.iwunu.iot.common.util.Result;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

@RestController
@Api(value = "/fackLock/member", tags = "人脸锁控制层接口", description = "人脸锁接口")
public class FacesLockController {
    @Autowired
    public RedisService  redisService;
    @Autowired
    public FaceLockService faceLockService;
    @Autowired
    public FaceLockMemberService faceLockMemberService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ImageMongodbService imageMongodbService;
    @Autowired
    private CmdIssuedMongodbService cmdIssuedMongodbService;
    @Autowired
    private SystemUserService systemUserService;
	@Autowired
	private FlockUserService flockUserService;
	@RequestMapping(value = "/bind" , method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> addFaceLock(
    		 @RequestHeader String Authorization,
    		@RequestBody FaceLockVo faceLockVo
    		){
    	 Result result = null ;
    	 String userId = tokenService.parseToken(Authorization);
    	 
    	if(faceLockVo==null || !StringUtils.isNoneEmpty(faceLockVo.getBaseCode())) {
    		 result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(),null);
           	 return new ResponseEntity<>(result, HttpStatus.OK);	
    	}
    	
    	String user =  DESUtil.encryptString("user");
    	String mac = faceLockVo.getMac().replace(":", "");
    	String clientId = mac.substring(mac.length()-8,mac.length()).toLowerCase();
    	if(clientId.contains(user)) {
    		clientId = clientId.replace(user, "");
    		
    	}
    	FaceLock lock = faceLockService.getFaceLockByMac(clientId);
    	if(lock!=null) {
    		faceLockService.del(lock.getId(),clientId);
    	}
    	 faceLockVo.setClientId(clientId);
    	 faceLockService.save(faceLockVo, userId);
    	 redisService.delKeys(clientId);//2021/10/27修改内容删除包含clientId所有缓存
    	 redisService.del(clientId  +"##_"+ ClientOpenTypeEnum.FACES.getType());
    	 redisService.del(clientId+ "##_" + ClientOpenTypeEnum.FEATURE.getType());
  		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),null);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
    
	@RequestMapping(value = "/updateLock/{lockId}" , method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> updateLock(
    		@RequestHeader String Authorization,
    		@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId,
    		@RequestBody LockUpdateVo faceLock
    		){
    	 Result result = null ;
    	 FaceLock  flock = faceLockService.update(faceLock,lockId);
  		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),flock);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
	
	@RequestMapping(value = "/del/{lockId}" , method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> delFaceLock(
    		@RequestHeader String Authorization,
    		@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId
    		){
    	Result result = null ;
     	 String imageType =  ClientOpenTypeEnum.DELFACES.getData();
      	 String pwdType =  ClientOpenTypeEnum.DELPWD.getData();
      	String cardType =  ClientOpenTypeEnum.CARD.getData();
    	FaceLock fl =faceLockService.getFaceLockByUUID(Long.valueOf(lockId));
    	if(fl==null) {
	   		 result = new Result(ResultCodeEnum.NOT_GATEWAY.getCode(), ResultCodeEnum.NOT_GATEWAY.getDesc(),null);
	       	 return new ResponseEntity<>(result, HttpStatus.OK);	
    	}
    	String userId = tokenService.parseToken(Authorization);
       if(fl.getOwnerId().equals(userId)) {
	    	String imagekey = fl.getClientId()+imageType;
	        String pwdkey = fl.getClientId()+pwdType;
	        redisService.rightPush(imagekey,"50");
	        redisService.rightPush(pwdkey, "100");
	        redisService.rightPush(cardType, "100");
	        faceLockService.del(Long.valueOf(lockId),fl.getClientId());
	        faceLockMemberService.delByLockId(lockId);
        }else {
        	faceLockMemberService.updateByLockIdAndUserId(Integer.valueOf(userId), lockId);
        }
 		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),null);
       	return new ResponseEntity<>(result, HttpStatus.OK);
    }
	/**
	 **获取锁二维码
	 * @param Authorization
	 * @param lockId
	 * @return
	 */
	@RequestMapping(value = "/getCode/{lockId}" , method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> getCode(
    		@RequestHeader String Authorization,
    		@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId
    		){
    	Result result = null ;
    	FaceLock fl =faceLockService.getFaceLockByUUID(Long.valueOf(lockId));
    	if(fl==null) {
	   		 result = new Result(ResultCodeEnum.GATEWAY_EIXT.getCode(), ResultCodeEnum.GATEWAY_EIXT.getDesc(),null);
	       	 return new ResponseEntity<>(result, HttpStatus.OK);	
    	}
    	JSONObject codeJson = new JSONObject();
    	codeJson.put("lockId", lockId);
    	codeJson.put("lockClientId", fl.getClientId());
    	String menber =  DESUtil.encryptString("menber");
    	String codeString = DESUtil.encryptString(codeJson.toJSONString());
 		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),menber+codeString);
       	return new ResponseEntity<>(result, HttpStatus.OK);
    }
    /**
     **添加成员
     * @param Authorization
     * @param code
     * @return
     */
	@RequestMapping(value = "/addfLockMember" , method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> addLockMember(
    		@RequestHeader String Authorization,
    		@RequestBody JSONObject json
    		){
    	Result result = null ;
    	String userId = tokenService.parseToken(Authorization);
    	String codeString =json.getString("code");
    	String member = DESUtil.encryptString("menber");
    	String user = DESUtil.encryptString("user");
    	String code = codeString.replace(member, "").replace(user, "");
    	JSONObject codeJson = JSONObject.parseObject(DESUtil.decryptString(code));
    	codeJson.put("userId", userId);
    	codeJson.put("remark", json.get("remark"));
    	
    	FaceLock fl =faceLockService.getFaceLockByUUID(Long.valueOf( codeJson.getInteger("lockId")));
    	if(fl.getOwnerId().equals(userId)) {
    		result = new Result(ResultCodeEnum.IS_OWNER.getCode(), ResultCodeEnum.IS_OWNER.getDesc(),null);
          	 return new ResponseEntity<>(result, HttpStatus.OK);	
    	}
    	FLockMember fm = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), codeJson.getInteger("lockId"));
    	if(fm == null) {
    		faceLockMemberService.sava(codeJson);
    	}else {
    		 result = new Result(ResultCodeEnum.SUB_EIXT.getCode(), ResultCodeEnum.SUB_EIXT.getDesc(),null);
           	 return new ResponseEntity<>(result, HttpStatus.OK);	
    	}
 		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),null);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
    /**
     ** 授权成员
     * @param Authorization
     * @param lockerMemberId
     * @return
     */
	@RequestMapping(value = "/auth/{lockMemberId}/{role}" , method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> auth(
    		@RequestHeader String Authorization,
    		@ApiParam(value = "锁成员ID", required = true) @PathVariable("lockMemberId") Integer lockMemberId,
    		@ApiParam(value = "锁成员角色", required = true) @PathVariable("role") Integer role
    		){
    	Result result = null ;
    	String userId = tokenService.parseToken(Authorization);
    	if(role==1) {role =  2;}
    	faceLockMemberService.auth(lockMemberId,role);
 		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),null);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
    /**
     * *锁列表
     * @param Authorization
     * @return
     */
	@RequestMapping(value = "/lockList" , method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> lockList(
    		@RequestHeader String Authorization
    		){
    	Result result = null ;
    	String userId = tokenService.parseToken(Authorization);
    	 List<Map<String, Object>> lockList = faceLockMemberService.selectByUserFaceLocks(Integer.valueOf(userId));
 		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),lockList);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
    /**
     * *我的锁列表
     * @param Authorization
     * @return
     */
	@RequestMapping(value = "/mylockList" , method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> mylockList(
    		@RequestHeader String Authorization
    		){
    	Result result = null ;
    	String userId = tokenService.parseToken(Authorization);
    	 List<Map<String, Object>> lockList = faceLockMemberService.selectMyFaceLocks(Integer.valueOf(userId));
 		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),lockList);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
    /**
     ** 锁详情
     * @param Authorization
     * @param lockerMemberId
     * @return
     */
	@RequestMapping(value = "/lockInfo/{lockId}" , method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> lockInfo(
    		@RequestHeader String Authorization,
    		@ApiParam(value = "锁ID", required = true) @PathVariable("lockId") Integer lockId
    		){
    	Result result = null ;
    	String userId = tokenService.parseToken(Authorization);
    	Map<String, Object> lockInfo = faceLockMemberService.findLockInfo(Integer.valueOf(userId), lockId);
 		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),lockInfo);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
    /**
     ** 锁详情
     * @param Authorization
     * @param lockerMemberId
     * @return
     */
	@RequestMapping(value = "/getlockByCode" , method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> getlockByCode(
    		@RequestHeader String Authorization,
    		@RequestBody JSONObject json
    		){
    	Result result = null ;
    	
    	String codeString =json.getString("code");
    	String member = DESUtil.encryptString("menber");
    	String user = DESUtil.encryptString("user");
    	String code = codeString.replace(member, "").replace(user, "");
    	JSONObject codeJson = JSONObject.parseObject(DESUtil.decryptString(code));
    	FaceLock fl = faceLockService.getFaceLockByUUID(codeJson.getLong("lockId"));
 		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),fl);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
    /**
     ** 授权成员列表
     * @param Authorization
     * @param lockerMemberId
     * @return
     */
	@RequestMapping(value = "/lockMemberList/{lockId}" , method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> lockMemberList(
    		@RequestHeader String Authorization,
    		@ApiParam(value = "锁ID", required = true) @PathVariable("lockId") Integer lockId
    		){
    		Result result = null ;
    	 List<Map<String, Object>> lockMemberList = faceLockMemberService.selectFaceLockMembers(lockId);
 		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),lockMemberList);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
    /**
     ** 待授权列表
     * @param Authorization
     * @param lockerMemberId
     * @return
     */
	@RequestMapping(value = "/authList/{lockId}" , method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> authList(
    		@RequestHeader String Authorization,
    		@ApiParam(value = "锁ID", required = true) @PathVariable("lockId") Integer lockId
    		){
    	 Result result = null ;
    	 List<Map<String, Object>> authList = faceLockMemberService.authList(lockId);
 		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),authList);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
    /**
     ** 删除成员
     * @param Authorization
     * @param lockerMemberId
     * @return
     */
	@RequestMapping(value = "/delfLockMember/{lockerMemberId}" , method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> delfLockMember(
    		@RequestHeader String Authorization,
    		 @ApiParam(value = "锁成员ID", required = true) @PathVariable("lockerMemberId") Integer lockerMemberId
    		){
    	Result result = null ;
    	FLockMember fl = faceLockMemberService.findById(Long.valueOf(lockerMemberId));
    	String userId = tokenService.parseToken(Authorization);
    	if(fl==null) {
   		 	result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(),null);
          	return new ResponseEntity<>(result, HttpStatus.OK);	
    	}
    	FLockMember fm = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), fl.getLockId());
    	if(userId.equals(fl.getUserId()+"")||fl.getRole()<fm.getRole()) {
    		result = new Result(ResultCodeEnum.NTO_ENOUGH_PRIVILEGES.getCode(), ResultCodeEnum.NTO_ENOUGH_PRIVILEGES.getDesc(),null);
         	return new ResponseEntity<>(result, HttpStatus.OK);		
    	}
    	List<ImageMongo> images = imageMongodbService.getSendImageDataByUser(lockerMemberId,fl.getLockClientId());
    	for(ImageMongo image:images) {
    		String type = 	ClientOpenTypeEnum.DELFACES.getData();
            String key = fl.getLockClientId()+type;
            redisService.rightPush(key,image.getPitNum().toString());
            cmdIssuedMongodbService.updateCmd(image.getClientId(), image.getPitNum(),ClientOpenTypeEnum.DELFACES.getType());
    	}
    	List<CmdIssued> cmds  = cmdIssuedMongodbService.getSendCmdByUser(lockerMemberId,fl.getLockClientId());
    	for(CmdIssued cmd:cmds) {
    		String type ="";
    		if(cmd.getType()==ClientOpenTypeEnum.DELPWD.getType()) {
    			type = 	ClientOpenTypeEnum.DELPWD.getData();
    		}else if(cmd.getType()==ClientOpenTypeEnum.DELCARD.getType()){
    			type = 	ClientOpenTypeEnum.DELCARD.getData();
    		}else if(cmd.getType()==ClientOpenTypeEnum.DELFINGER.getType()) {
    			type = 	ClientOpenTypeEnum.DELFINGER.getData();
    		}
            String key = fl.getLockClientId()+type;
            redisService.rightPush(key,cmd.getPitNum().toString());
            cmdIssuedMongodbService.updateCmd(fl.getLockClientId(), cmd.getPitNum(),ClientOpenTypeEnum.DELPWD.getType());
    	}
    	 faceLockMemberService.delByLockMemberId(Long.valueOf(lockerMemberId));
 		 result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),null);
       	 return new ResponseEntity<>(result, HttpStatus.OK);
    }
    
    /**
     ** 转换成员
     * @param Authorization
     * @param lockerMemberId
     * @return
     */
	@RequestMapping(value = "/changeMember/{receiveId}/{isBussiness}" , method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> changeMember(
    		@RequestHeader String Authorization,
    		@ApiParam(value = "锁取人ID", required = true) @PathVariable("receiveId") Integer receiveId,
    		@ApiParam(value = "是否商户", required = true) @PathVariable("isBussiness") boolean isBussiness,
    		@RequestBody JSONObject lockIds
    		){
    	Result result = null ;
    	String[] arr = lockIds.getString("lockIds").split(",");
    	List<String> list = Arrays.asList(arr);
    	List<Integer> lockIdArray = new ArrayList<Integer>();
    	for(String lockId :list) {
    		lockIdArray.add(Integer.valueOf(lockId));
//    		FaceLock flock = faceLockService.getFaceLockByUUID(Long.valueOf(lockId));
//    		String typepwd =  ClientOpenTypeEnum.DELPWD.getData();
//         	String typecard =  ClientOpenTypeEnum.DELCARD.getData();
//         	String typefingle =  ClientOpenTypeEnum.DELFINGER.getData();
//         	String typefaces =  ClientOpenTypeEnum.DELFACES.getData();
//            String key = flock.getClientId()+typepwd;
//            redisService.rightPush(key,ApartmentConstant.pitNum.toString());
//            String  cardkey = flock.getClientId()+typecard;
//            redisService.rightPush(cardkey,ApartmentConstant.pitNum.toString());
//            String finglekey = flock.getClientId()+typefingle;
//            redisService.rightPush(finglekey, ApartmentConstant.pitNum.toString());
//            String faceskey = flock.getClientId()+typefaces;
//            redisService.rightPush(faceskey,ApartmentConstant.imagePitNum.toString());
    	}
    	if(isBussiness) {
    		FLockUser fl = flockUserService.getFlackUserByUserId(Long.valueOf(receiveId));
    		SystemUser systemUser = systemUserService.findSystemUser(fl.getPhone());
    		if(systemUser==null){
    	 		result = new Result(ResultCodeEnum.NOT_BUSSINESS_USER.getCode(), ResultCodeEnum.NOT_BUSSINESS_USER.getDesc(),null);
    	       	return new ResponseEntity<>(result, HttpStatus.OK);
    		}
    		if(systemUser.getIsPush()) {
    			faceLockMemberService.changePushMember(lockIdArray,receiveId,systemUser.getUserNo());
    		}else {
    			faceLockMemberService.changeMember(lockIdArray,receiveId,systemUser.getUserNo());
    		}
    	}else {
    		faceLockMemberService.changeMember(lockIdArray,receiveId,null);
    	}
    	faceLockMemberService.delByLockIds(lockIdArray);
 		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),null);
       	return new ResponseEntity<>(result, HttpStatus.OK);
    }
}
